<template>
  <!-- 分发接收  -->
  <div v-loading="loading">
    <!-- 模块名称 -->
    <NavigationComponent />

    <!-- 头部搜索 -->
    <div class="search-top">
      <!-- 搜索 -->
      <el-input
        :placeholder="$t('teamDist.searchContent')"
        prefix-icon="el-icon-search"
        v-model="searchValue"
        class="inputClass"
        @keyup.enter.native="getTableData('reset')"
      >
      </el-input>

      <el-divider direction="vertical"></el-divider>
      <!--选项  -->
      <div @click="getChange('mySend')" class="link-btn" :class="selectValue == 'mySend' ? 'isActive' : ''">{{ $t('teamDist.distribute') }}</div>

      <div @click="getChange('myReceive')" class="link-btn" :class="selectValue == 'myReceive' ? 'isActive' : ''">{{ $t('teamDist.receive') }}</div>
    </div>

    <!-- 内容 -->
    <div class="table_box">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :row-style="{ height: '52px' }"
        :header-row-style="{ height: '52px' }"
        :highlight-current-row="true"
      >
        <el-table-column :label="$t('teamDist.fileName')" prop="fileName" show-overflow-tooltip />
        <el-table-column prop="distributorName" :label="$t('teamDist.distributor')" show-overflow-tooltip />
        <el-table-column prop="createTime" :label="$t('teamDist.path')" v-if="selectValue == 'mySend'" key="createTime" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.type == '0' ? $t('teamDist.myDocuments') : $t('teamDist.teamDocumentation') }}
          </template>
        </el-table-column>
        <el-table-column prop="distributeTime" :label="$t('teamDist.distributionTime')" show-overflow-tooltip />
        <el-table-column prop="deleteBy" :label="$t('commen.operation')" fixed="right" align="center">
          <template v-slot="operate">
            <span v-if="selectValue == 'mySend'">
              <el-link type="primary" @click="getViewAndBack(operate.row, false)">{{ $t('teamDist.check') }}</el-link>
              <el-link type="primary" @click="getViewAndBack(operate.row, 'true')" class="link-margin">{{ $t('teamDist.revocation') }}</el-link>
            </span>

            <el-link type="primary" v-else @click="getReceive(operate.row)">{{ $t('teamDist.reception') }}</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
      @size-change="getSizeChange"
      @current-change="getPageChange"
      :current-page="commonParams.page + 1"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="commonParams.size"
      layout="total, prev, pager, next, sizes"
      :total="commonParams.total"
    />

    <!-- 我的分发查看和撤回 -->
    <div>
      <el-dialog :title="dialog.title" v-model="dialog.visibleDialog" width="550px" :before-close="getClose" class="visible-dialog">
        <div v-if="selectValue == 'mySend'" v-loading="dialog.treeLoading">
          <el-table :data="dialog.personList" tooltip-effect="dark" style="width: 100%" border class="dialog-table" :highlight-current-row="true">
            <el-table-column :label="$t('teamDist.recipient')" prop="senderName" align="center"></el-table-column>
            <el-table-column :label="$t('teamDist.acceptingState')" align="center">
              <template v-slot="receive">
                <span :class="receive.row.receive == 0 ? 'colorRed' : 'colorGreen '">
                  {{ receive.row.receive == 0 ? $t('teamDist.notReceived') : $t('teamDist.received') }}
                </span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="dialogChangeSise"
            @current-change="dialogChangePage"
            :current-page="dialog.page"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="dialog.size"
            layout="total,  prev, pager, next,sizes"
            :total="dialog.total"
          ></el-pagination>
        </div>

        <div v-else v-loading="dialog.treeLoading">
          <el-tree
            ref="treeRestore"
            :data="dialog.treeRestoreList"
            :props="dialog.defaultProps"
            node-key="id"
            class="filter-tree"
            :lazy="true"
            :load="loadNode"
            :highlight-current="true"
            :default-expanded-keys="dialog.expandedKeys"
            :expand-on-click-node="false"
            @node-click="treeRestoreNodeClick"
          >
            <template #default="{ node, data }">
              <svg-icon :icon-class="node.expanded ? 'file-open' : 'file-close'"></svg-icon>
              <span>{{ node.label }}</span>
            </template>
          </el-tree>
          <div class="path">{{ $t('teamDist.restorePath') }} {{ dialog.treeRestorePathObj.path.replace(/\//g, '\\') }}</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="getClose">
            {{ selectValue == 'mySend' ? $t('teamDist.close') : $t('teamDist.cancel') }}
          </el-button>
          <el-button @click="getBack" type="primary" v-if="dialog.isHaveBack"> {{ $t('teamDist.revocation') }} </el-button>
          <el-button type="success" @click="getReset" v-if="selectValue == 'myReceive'"> {{ $t('teamDist.reset') }} </el-button>
          <el-button v-if="selectValue == 'myReceive'" @click="debounce_getComfirm"> {{ $t('commen.confirm') }} </el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ApiPerReceiveFile,
  ApiPerQueryDistribute,
  ApiPerQuerySend,
  ApiPerFilesSender,
  ApiPerFilesDelete,
  apiTreeFileSelectTree,
  ApiPerSelectPersonalTree
} from '@/api/personDoc/personDocApi';
import NavigationComponent from '@/views/personDoc/personal-component/navigation-component.vue'; // 导航信息
import { debounce } from '@/utils/yuUtils.js';

const { proxy } = getCurrentInstance() as any;
// 获取路由实例
const route = useRoute();
const loading = ref(false);
const searchValue = ref('');
const selectValue = ref('mySend');
const tableData = ref([]);
const commonParams = reactive({ page: 0, size: 10, total: 0 });

const dialog = reactive({
  title: '',
  visibleDialog: false,
  personList: [],
  isHaveBack: false,
  page: 1,
  size: 10,
  total: 0,
  item: { id: '' },
  // 树结构
  defaultProps: {
    children: 'children',
    label: 'realName',
    isLeaf: 'leaf'
  },
  treeLoading: false,
  expandedKeys: [0],
  treeRestoreList: [],
  treeRestorePathObj: { path: '', id: '' }
});

//获取表格数据
const getTableData = async (reset) => {
  loading.value = true;
  if (reset == 'reset') {
    commonParams.page = 0;
    commonParams.size = 10;
  }

  let oParam = {
    page: commonParams.page,
    size: commonParams.size,
    modules: 'personal',
    fileName: searchValue.value || null
  };

  let res;
  if (selectValue.value == 'myReceive') {
    //  我的接收
    res = await ApiPerQuerySend(oParam);
  } else {
    // 我的分发
    res = await ApiPerQueryDistribute(oParam);
  }

  loading.value = false;
  tableData.value = res.data.rows;
  commonParams.total = res.data.total;
};
// 查看 和 撤回
const getViewAndBack = (item, isHaveBack) => {
  dialog.item = item;
  dialog.visibleDialog = true;
  dialog.isHaveBack = isHaveBack;
  dialog.title = proxy?.$t('teamDist.tip1');
  getPersonList(item, 'reset');
};

// 接收人列表
const getPersonList = (item, reset) => {
  dialog.treeLoading = true;
  if (reset == 'reset') {
    dialog.page = 1;
    dialog.size = 10;
  }
  let oParam = {
    distributeId: item.id,
    page: dialog.page - 1,
    size: dialog.size
  };
  ApiPerFilesSender(oParam).then((res) => {
    // console.log('🚀 ~ ApiPerFilesSender ~ res:', res);
    if (res.code == 200) {
      dialog.personList = res.data.rows;
      dialog.total = res.data.total;
      dialog.treeLoading = false;
    }
  });
};

// 接收
const getReceive = (item) => {
  dialog.item = item;
  dialog.visibleDialog = true;
  dialog.title = proxy.$t('teamDist.tip4');
  getReset();
};
// 接收时重置
const getReset = () => {
  dialog.treeLoading = true;
  let oParam = {
    sortDesc: 'type,create_time'
  };
  ApiPerSelectPersonalTree(oParam)
    .then((res) => {
      // console.log('🚀 ~ getReset ~ res:', res);

      dialog.treeRestorePathObj = res.data;
      dialog.treeRestoreList = res.data.children.filter((item) => item.type == 'folder');
      dialog.treeLoading = false;
    })
    .catch((err) => {
      dialog.treeLoading = false;
    });
};

//-选择树
const loadNode = (node, resolve) => {
  if (node.level == 0) {
    return resolve(node.data);
  }
  apiTreeFileSelectTree({
    parentId: node.key,
    sortDesc: 'type,create_time'
  }).then((res: any) => {
    // console.log('🚀 ~ loadNode ~ res:', res);

    let childrenArr = res.data.children.filter((item) => item.type == 'folder');
    return resolve(childrenArr);
  });
};

// 单击节点
const treeRestoreNodeClick = (data, node) => {
  dialog.treeRestorePathObj = data;
};

const debounce_getComfirm = debounce(() => {
  getComfirm();
}, 500); // 调整延迟时间以适应你的需求

// 接收人确定
const getComfirm = () => {
  let oParam = {
    id: dialog.item.id,
    parentId: dialog.treeRestorePathObj.id
  };

  ApiPerReceiveFile(oParam).then((res) => {
    getClose();
    ElMessage.success(proxy.$t('teamDist.tip5'));
    getTableData('reset');
  });
};

// 切换页数
const getSizeChange = (val) => {
  commonParams.size = val;
  getTableData('');
};

// 切换条数
const getPageChange = (val) => {
  commonParams.page = val - 1;
  getTableData('');
};

// 切换size  --dialog
const dialogChangeSise = (val) => {
  dialog.size = val;
  getPersonList(dialog.item, 'reset');
};

// 切换page --dialog
const dialogChangePage = (val) => {
  dialog.page = val;
  getPersonList(dialog.item, 'reset');
};

// 接收人撤回
const getBack = () => {
  let del = dialog.personList.findIndex((item) => item.receive == 0);
  if (!del) {
    ElMessageBox.confirm(proxy.$t('teamDist.tip2'), proxy.$t('commen.title'), {
      confirmButtonText: proxy.$t('commen.confirm'),
      cancelButtonText: proxy.$t('commen.cancel'),
      type: 'warning'
    })
      .then(() => {
        getFilesDistributeDelete(dialog.item.id);
      })
      .catch();
  } else {
    getFilesDistributeDelete(dialog.item.id);
  }
};

// 接收人撤回调接口
const getFilesDistributeDelete = (id) => {
  let oParam = {
    id: id
  };

  ApiPerFilesDelete(oParam).then((res) => {
    if (res.code == 200) {
      getClose();
      getTableData('reset');
      ElMessage.success(proxy.$t('teamDist.tip3'));
    }
  });
};

// 关闭弹窗
const getClose = () => {
  dialog.visibleDialog = false;
  dialog.item = { id: '' };
  dialog.isHaveBack = false;
  dialog.personList = [];
  dialog.treeRestorePathObj = { path: '', id: '' };
};

// 切换 链接分享 | 收到的链接分享
const getChange = (val) => {
  tableData.value = [];
  selectValue.value = val;
  getTableData('reset');
};

onMounted(() => {
  getTableData('reset');
});
</script>

<style scoped lang="scss">
:deep(.el-input__inner) {
  border: none;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

// ::deep(.el-input__wrapper) {
//   box-shadow: none;
//   border: none;
// }

:deep(.el-input__wrapper) {
  box-shadow: none;
  border: none;
}

.search-top {
  display: flex;
  align-items: center;
  height: 48px;
  padding-right: 20px;
  margin-left: 20px;
  border-bottom: 1px solid #eee;

  .inputClass {
    width: 220px;
  }

  .link-btn {
    background: #f5f5f5;
    border-radius: 22px 22px 22px 22px;
    font-size: 12px;
    padding: 5px 13px;
    color: #666;
    margin-left: 20px;
    cursor: pointer;
  }

  .isActive {
    color: #6698ff;
    background-color: #eff4ff;
  }

  //

  :deep(.link-select) {
    border: 1px solid #909399ad;
    background: #6698ff;
  }
}

:deep(.el-select-dropdown__item.hover, .el-select-dropdown__item:hover) {
  background-color: #909399ad;
}

.table_box {
  overflow: auto;
  height: calc(100vh - 210px);
  margin-left: 20px;

  .link-margin {
    margin: 0px 5px;
  }
}

.el-pagination {
  // margin-top: 25px;
  padding: 0px 16px;
}

:deep(.el-dialog__body) {
  padding-bottom: 0px;
}

.visible-dialog {
  .dialog-table {
    height: 50vh;
    overflow-y: auto;

    .colorRed {
      color: #f56c6c;
    }

    .colorGreen {
      color: #67c23a;
    }
  }

  .el-pagination {
    margin-top: 0px;
  }

  .path {
    margin-top: 10px;
  }
}
</style>
